﻿@using System.Text.RegularExpressions;
@using WishlistUtilities;

<h1>Add Item</h1>

@{
	
	PageData["Title"] = "Add Item to Wishlist";

	WebSecurity.RequireAuthenticatedUser();	

	if (!Request["wishlistId"].IsInt() || (Request["returnUrl"] == null)) {
		Response.Redirect("~/Shared/Errors/Error");
	}

	var wishlistId = Request["wishlistId"].AsInt();
	var returnUrl = Request["returnUrl"];

	var db = Database.Open("wishlistdb");

    var name = "";
    var link = "";
    var price = "";

    var errorMessage = "";

	if (IsPost) {
		// verify the person adding the item owns the list
		var listToEdit = db.QuerySingle("SELECT Id FROM List WHERE Id = @0 AND WishlistUserId = @1", 
			wishlistId, WebSecurity.CurrentUserId);

		if (listToEdit == null) {
			// user doesn't own this list
			Response.Redirect("~/Shared/Errors/Error");
		}

		if (Request["action"] == "Cancel") {
			Context.RedirectLocal(returnUrl);
		}

		if (Request["action"] == "Add") {
			name = Request["name"];
			link = Request["link"];
			price = Request["price"];			

			if (name.IsEmpty()) {
				errorMessage += "<li>Item name is required.</li>";
			}

			if (link.IsEmpty()) {
				errorMessage += "<li>Link is required.</li>";
			} else {
				if (!ValidationUtility.IsValidUrl(link)) {
					errorMessage += "<li>Link is invalid.</li>";
				}
			}

			if (!price.IsDecimal() || (price.AsDecimal() < 0)) {
				errorMessage += "<li>A valid price is required.</li>";
			}

			if (errorMessage.IsEmpty()) {
				try {
					db.Execute("INSERT INTO Item (Name, Link, Price, ListId, Claimed) VALUES (@0, @1, @2, @3, @4)",
						name, link, price, wishlistId, false);
				} catch (Exception) {
					Response.Redirect("~/Shared/Errors/Error");
				}

				Context.RedirectLocal(returnUrl);
			}
		}
	}

    if (!errorMessage.IsEmpty()) {
        @RenderPage("~/Shared/Errors/_FormInputError.cshtml", errorMessage);
    }
}

<div id="addItem">
	<span>
		<form id="validateForm" method="post" action="">
			<fieldset>				
					@RenderPage("~/Shared/_PrePopInputFormField.cshtml",
                        new { labelName = "name", labelDisplay = "Name:", maxLength = 100, inputValue = name, required = true})
					@RenderPage("~/Shared/_PrePopInputFormField.cshtml",
                        new { labelName = "price", labelDisplay = "Price:", required = true, 
                            validationClasses = "number", validationAttributes = "min=\"0\"", inputValue = price})
					@RenderPage("~/Shared/_PrePopInputFormField.cshtml",
                        new { labelName = "link", labelDisplay = "Link:", inputValue = link.IsEmpty() ? "http://" : link, 
                            required = true, validationClasses = "url"})
					<input name="wishlistId" type="hidden" value=@wishlistId />
					<input name="returnUrl" type="hidden" value="@returnUrl" />
					<div class="submit-group">
						<input name="action" type="submit" value="Add" onclick="javascript:$('#validateForm').validate()" />
						<input name="action" type="submit" value="Cancel" class="cancel" />
					</div>
			</fieldset>
		</form>
	</span>
</div>